#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author : zaniu(zzaniu@126.com)
# @Time   : 2021/6/23 14:51 
# @Desc   :
# 
#                   _ooOoo_
#                  o8888888o
#                  88" . "88
#                  (| -_- |)
#                  O\  =  /O
#               ____/`---'\____
#             .'  \\|     |//  `.
#            /  \\|||  :  |||//  \
#           /  _||||| -:- |||||-  \
#           |   | \\\  -  /// |   |
#           | \_|  ''\---/''  |   |
#           \  .-\__  `-`  ___/-. /
#         ___`. .'  /--.--\  `. . __
#      ."" '<  `.___\_<|>_/___.'  >'"".
#     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
#     \  \ `-.   \_ __\ /__ _/   .-` /  /
# =====`-.____`-.___\_____/___.-`____.-'=====
#                   `=---='
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#             佛祖保佑       永无BUG
#
from datetime import datetime

import grpc
from grpc._channel import _InactiveRpcError

from learn_grpc_001.proto import hello_pb2_grpc, hello_pb2


channel = grpc.insecure_channel('172.18.2.184:50051')


class DefaultValueClientInterceptor(grpc.UnaryUnaryClientInterceptor):

    def intercept_unary_unary(self, continuation, client_call_details, request):
        print(f"continuation = {continuation}， client_call_details = {client_call_details}， request = {request}")
        # if client_call_details.metadata:
        #     client_call_details.metadata = *client_call_details.metadata, ("token", "bt 123456789")
        # else:
        #     client_call_details.metadata = (("token", "bt 123456789"),)
        start = datetime.now()
        rsp = continuation(client_call_details, request)
        last = datetime.now()-start
        print(f"last = {last}")
        print(f"last.microseconds/1000 = {last.microseconds/1000}")
        # print(f"用时: {datetime.now()-start}")
        return rsp


def hello():
    intercept_channel = grpc.intercept_channel(channel, DefaultValueClientInterceptor())
    stub = hello_pb2_grpc.GreeterStub(intercept_channel)
    # res = stub.SayHello(hello_pb2.HelloRequest(name="沙雕"))
    # print("Greeter client received: " + res.message)
    response, call = stub.SayHello.with_call(
        hello_pb2.HelloRequest(name='沙雕'),
        metadata=(
            ('token', 'bt 123456789'),
            ('name', 'hugong2'),
            ('password', 'wenjunai93'),
        )
    )
    print("Greeter client received: " + response.message)
    print(f"call = {call}")


def addInt(value1: int, value2: int):
    intercept_channel = grpc.intercept_channel(channel, DefaultValueClientInterceptor())
    stub = hello_pb2_grpc.AddServerStub(intercept_channel)
    try:
        response = stub.AddInt(hello_pb2.AddIntRequest(value1=value1, value2=value2))
    except _InactiveRpcError as e:
        print(f"e.code() = {e.code()}")
        print(f"e.details() = {e.details()}")
        return 0
    print("addInt client received: ", response.message)
    return response.message


def addFloat(value1: float, value2: float):
    # 获取存根，其实就是指定channel发送固定字符串
    intercept_channel = grpc.intercept_channel(channel, DefaultValueClientInterceptor())
    stub = hello_pb2_grpc.AddServerStub(intercept_channel)
    # 用存根调用远程方法
    res = stub.AddFloat(hello_pb2.AddFloatRequest(value1=value1, value2=value2))
    return res.message


if __name__ == '__main__':
    hello()
    print(addInt(1, 4))
    # print(addFloat(1, 4))
